<template>
    <div class="jianzhan-wrapper">
        <Crumb name="Role Manage"/>
        <div class="jianzhan-content">
            <div class="left">
                <div class="title" @click="
                roleShow = true
                clear()
        ">Role List
                    <i class="el-icon-plus"></i>
                </div>
                <el-tree
                        :data="roleList"
                        node-key="id"
                        default-expand-all
                        :expand-on-click-node="false"
                        highlight-current
                        @node-click="setCurrent"
                        :props="props"
                >
                  <span class="my-tree-item" slot-scope="{ node, data }">
                    <span>{{node.label}}</span>
                       <span>
                          <el-button
                                  type="text"
                                  size="mini"
                                  @click="
                                  roleShow = true
                                  parentName = node.parent.data.name
                                  ruleForm = data
                                ">
                           <i class="el-icon-edit"></i>
                          </el-button>
                        </span>
                  </span>
                </el-tree>
            </div>
            <div class="right">
                <el-tabs v-model="auth" type="card">
                    <el-tab-pane label="Role & Auth" name="auth">
                        <el-tree
                                ref="roleTree"
                                :data="roleTree"
                                :default-checked-keys="checkedRole"
                                node-key="id"
                                default-expand-all
                                :expand-on-click-node="false"
                                highlight-current
                                show-checkbox=""
                                :props="props"
                        >
                        </el-tree>
                        <el-button type="primary" @click="_changeAcls">Save</el-button>
                    </el-tab-pane>
                    <el-tab-pane label="Role & User" name="user">
                        <el-transfer filterable v-model="roleUserSelected" :data="roleUser"
                                     :props="{key:'id',label:'username'}"
                                     :titles="['Unselect','Selected']"/>
                        <el-button type="text" @click="saveUser">Save</el-button>
                    </el-tab-pane>
                </el-tabs>
            </div>
            <el-dialog title="Role" :visible.sync="roleShow" width="40%">
                <el-form :model="ruleForm" ref="ruleForm" label-width="200px" class="demo-ruleForm">
                    <el-form-item label="Name">
                        <el-input v-model="ruleForm.name"/>
                    </el-form-item>
                    <el-form-item label="status">
                        <el-select v-model="ruleForm.status">
                            <el-option :value=0 label="Available"/>
                            <el-option :value=1 label="Frozen"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="Remark">
                        <el-input type="textarea" v-model="ruleForm.remark"/>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                        <el-button @click="roleShow = false">Cancel</el-button>
                        <el-button type="primary" @click="saveRole">Confirm</el-button>
                    </span>
            </el-dialog>

        </div>
    </div>
</template>

<script>
    import {ERROR_OK} from "../../util/config";
    import {getChecked} from "../../util";
    import {
        getRoleList, addRole, modRole, getRoleTree, getRoleUser, changeAcls, changeUsers
    } from "../../api/auth";
    import Crumb from '@/components/common/crumb.vue'

    export default {
        name: "user-manage",
        data() {
            return {
                roleList: [],
                roleTree: [],
                roleUserSelected: [],
                roleUser: [],
                checkedRole: [],
                props: {
                    label: 'name',
                    children: 'aclList'
                },
                auth: "auth",
                current: {},
                visible2: false,
                userShow: false,
                roleShow: false,
                ruleForm: {
                    name: '',
                    status: '',
                    remark: ''
                }
            }
        },
        filters: {
            transfromStatus(status) {
                const statusList = ['Not active', 'Active', 'Deleted'];
                return statusList[status]
            }
        },
        created() {
            this._getRole();
        },
        components: {
            Crumb
        },
        methods: {
            setCurrent(data) {
                this.current = data;
                if (this.auth === 'auth') {
                    this._getRoleTree()
                } else if (this.auth === 'user') {
                    this._getRoleUser()
                }
            },
            async _changeAcls() {
                const checkedRole = this.$refs.roleTree.getCheckedKeys(true).join(',');
                const {status} = await changeAcls({roleId: this.current.id, aclIds: checkedRole});
                if (status === ERROR_OK) {
                    const h = this.$createElement;
                    this.$notify({
                        title: 'Change Successfully',
                        message: h('i', {style: 'color: teal'}, 'Authority has been changed successfully!')
                    });
                }
            },
            clear() {
                this.ruleForm = {
                    id: '',
                    name: '',
                    status: '',
                    remark: ''
                }
            },
            async saveRole() {
                const {id, name, status, remark} = this.ruleForm;
                if (id) {
                    const {status: status1} = await modRole({id, name, status, remark});
                    if (status1 === ERROR_OK) {
                        this.$message({
                            message: 'Modify Role Successfully',
                            type: 'success'
                        })
                    } else {
                        this.$message({
                            message: 'Modify Role Error',
                            type: 'error'
                        })
                    }
                } else {
                    const {status: status1} = await addRole({name, status, remark});
                    if (status1 === ERROR_OK) {
                        this.$message({
                            message: 'Add Role Successfully',
                            type: 'success'
                        });
                        this._getRole()
                    } else {
                        this.$message({
                            message: 'Add Role Error',
                            type: 'error'
                        })
                    }
                }
                this.roleShow = false
            },
            async saveUser() {
                const userIds = this.roleUserSelected.join(',');
                const {status} = await changeUsers({roleId: this.current.id, userIds});
                if (status === ERROR_OK) {
                    this.$message({
                        type: 'success',
                        message: 'Change User Successfully'
                    })
                } else {
                    this.$message({
                        message: 'error,try again',
                        type: 'error'
                    })
                }
            },
            async _getRole() {
                let {status, data} = await getRoleList();
                if (status === ERROR_OK) {
                    this.roleList = data
                }
            },
            async _getRoleTree() {
                function combine(arr) {
                    if (arr.length) {
                        arr.forEach(item => {
                            item.id = item.id + 10086; //防止冲突id的出现
                            item.aclList = item.aclList.concat(item.aclModuleList);
                            if (item.aclModuleList.length) {
                                combine(item.aclModuleList)
                            }
                        })
                    }
                    return arr;
                }

                const {status, data} = await getRoleTree(this.current.id);
                if (status === ERROR_OK) {
                    this.roleTree = combine(data); //递归便利树，把二分结构合并
                    this.checkedRole = getChecked(this.roleTree)
                }
            },
            async _getRoleUser() {
                const {status, data} = await getRoleUser(this.current.id);
                if (status === 0) {
                    this.roleUserSelected = data.selected.map(item => item.id);
                    this.roleUser = data.unselected.concat(data.selected);
                }
            }
        },
        watch: {
            auth(auth) {  //判断选择面板
                if (this.current.id) {
                    if (auth === 'auth') {
                        this._getRoleTree();
                    } else if (auth === 'user') {
                        this._getRoleUser()
                    }
                }
            }
        }
    }
</script>

<style scoped lang="scss">
    .jianzhan-wrapper {
        background: #fff;
        .jianzhan-content {
            padding: 5px 0;
            .left, .right {
                text-align: left;
                overflow: hidden;
                display: inline-block;
                vertical-align: top;
                .title {
                    user-select: none;
                    text-align: center;
                    cursor: pointer;
                    border-radius: 2px;
                    width: 150px;
                    height: 30px;
                    line-height: 30px;
                    background: #409EFF;
                    color: #fff;
                    padding: 0 20px;
                    &:hover {
                        background: #3a8ee6;
                    }
                }
            }
            .left {
                width: 30%;
                margin-right: 30px;
                .my-tree-item {
                    flex: 1;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    padding-right: 8px;
                }
            }
            .right {
                width: 65%;
            }
        }
    }
</style>